<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table {
      border: 1px solid #ddd;
      border-collapse: collapse;
      border-spacing: 0;
    }

    td,
    th {
      border: 1px solid #ddd;
      padding: 20px;
      line-height: 40px;
    }
  </style>
</head>

<body>
  <button id="btn">点击访问数据</button>
  <br>
  <table>
    <thead>
      <tr>
        <th>姓名</th>
        <th>性别</th>
        <th>电话</th>
        <th>成绩</th>
      </tr>
    </thead>
    <tbody id="mybody">

    </tbody>
  </table>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/Mock.js/1.0.0/mock-min.js"></script>
<script>
  let btn = document.getElementById("btn");
  let mybody = document.getElementById("mybody");

  let users = null;

  Mock.mock(/users/, "get", function () {
    let data = Mock.mock({
      "users|10-15": [{
        "username": "@cname()",
        "sex|1": ["男", "女"],
        "tel": /^1[3-9]\d{9}$/,
        "score|1-100": 1
      }]
    }).users

    return data;
  })

  const ajaxPromise = function (param) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.open(param.type || "get", param.url, true);
      xhr.send(param.data || "");

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            if (param.dataType === "json") {
              resolve(JSON.parse(xhr.responseText));
            }
            else {
              resolve(xhr.responseText);
            }

          }
          else {
            reject(xhr.responseText);
          }
        }
      }
    })
  }


  btn.onclick = async function () {
    users = await ajaxPromise({
      type: "get",
      url: "/users",
      dataType: "json"
    })

    setHTML(users);
  }



  function setHTML(users) {
    for (let i = 0; i < users.length; i++) {
      let user = users[i];
      let str = `<tr>
        <td>${user.username}</td>
        <td>${user.sex}</td>
        <td>${user.tel}</td>
        <td>${user.score}</td>
      </tr>`
      mybody.innerHTML += str
    }
  }
</script>

</html>